﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MeDialog : MonoBehaviour
{
	public string name;

	void Awake() {
		setDialog(name, this);
	}
	
	public virtual void show() {
		gameObject.SetActive(true);
	}
	
	public virtual void close() {
		gameObject.SetActive(false);
	}

	public class MeDialogRetain {
		
		public MeDialog dialog;
		
		public int dialogCongruence;
	}

	private static MeDialogRetain DialogRetain;

	private static Dictionary<string, MeDialogRetain> DialogRetainDic = new Dictionary<string, MeDialogRetain>();

	public static void setDialog(string name, MeDialog dialog) {
		//Debug.Log("MedialogSetDialog:" + name + ":" + dialog);
		MeDialogRetain retain = null;
		if(name == null || name.Length == 0) {
			if(DialogRetain == null) {
				DialogRetain = new MeDialogRetain();
			}

			retain = DialogRetain;

		} else {
			DialogRetainDic.TryGetValue(name, out retain);
			if(retain == null) {
				retain = new MeDialogRetain();
				DialogRetainDic.Add(name, retain);
			}
		}

		if(retain.dialog != null && retain.dialog) {
			MonoBehaviour.Destroy(retain.dialog);
		}

		retain.dialog = dialog;
		if(retain.dialogCongruence <= 0) {
			dialog.gameObject.SetActive(false);
		}
	}

	public static void showDialog(string name) {
		if(name == null) {
			return;
		}

		showDialog(DialogRetain);
		if(name.Length > 0) {
			MeDialogRetain retain = null;
			DialogRetainDic.TryGetValue(name, out retain);
			if(retain != null) {
				showDialog(retain);
			}
		}
	}

	public static void showDialog(MeDialogRetain retain) {
//		if(retain != null) {
//			Debug.Log("showDialog:" + retain.dialog + "=>" + retain.dialogCongruence);
//		}

		if(retain != null && retain.dialogCongruence++ == 0) {
			retain.dialog.show();
		}
	}

	public static void closeDialog(string name) {
		if(name == null) {
			return;
		}
		
		closeDialog(DialogRetain);
		if(name.Length > 0) {
			MeDialogRetain retain = null;
			DialogRetainDic.TryGetValue(name, out retain);
			if(retain != null) {
				closeDialog(retain);
			}
		}
	}

	public static void closeDialog(MeDialogRetain retain) {
//		if(retain != null) {
//			Debug.Log("closeDialog:" + retain.dialog + "=>" + retain.dialogCongruence);
//		}

		if(retain != null && --retain.dialogCongruence == 0) {
			retain.dialog.close();
		}
	}
}
